home *** CD-ROM | disk | FTP | other *** search
- Path: news.chattanooga.net!usenet
- From: "Eric W. Bradway" <ebradway@microsports.com>
- Newsgroups: comp.lang.c
- Subject: Re: Help using qsort to sort pointers to a structure
- Date: Tue, 30 Jan 1996 12:52:54 -0500
- Organization: Micro Sports, Inc.
- Message-ID: <310E5AF6.5B55@microsports.com>
- References: <4eg8rp$2oo_001@news2.cts.com>
- NNTP-Posting-Host: 205.244.28.38
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0b5 (Win95; I)
-
- William Rinehart wrote:
- > qsort((void *)data, (size_t)4, sizeof(struct alpha *), compname);
-
- sizeof(struct alpha *) gives the size of a pointer to struct alpha
- (i.e., 4 on most machines) so when qsort starts copying stuff around it
- only copies the first four byte!
-
- > int
- > compname(const void *arg1, const void *arg2)
- > {
- > /* cast arg1 and arg2 as pointers to pointers, then derefence
- > so that strcmp gets "regular" pointer as arguments */
- > return (strcmp((*(struct alpha**)arg1)->names, (*(struct alpha**)arg2)->names));
- > }
-
- Here you want to cast to (struct alpha *) only so it knows what type
- arg1 and arg2 really are. Casting to (struct alpha **) make the compiler
- think that what arg1 is pointing to is a pointer and when you
- dereference this non-pointer it is pointing to someplace in
- never-never-land (actually in this case, for the first string it would
- be whatever your system translated the four bytes "aaa\0" to).
-
- I'm not much of an expert on this (I had to look at some of my code that
- works to tell you exactly what is wrong) but I would suggest getting a
- good ANSI C book that provides examples for functions like qsort. I use
- qsort so infrequently myself that I always start by reviewing working
- code (and usually just copying and modifying it).
-
- Good luck...
- -Eric
-